package com.cn.qgx428.lazydiary.Utils

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.content.FileProvider
import android.text.TextUtils
import com.cn.qgx428.lazydiary.APP
import com.cn.qgx428.lazydiary.R
import com.cn.qgx428.lazydiary.local.LAMessege
import com.cn.qgx428.lazydiary.local.LAction
import com.cn.qgx428.lazydiary.local.LActionWacher
import com.cn.qgx428.lazydiary.local.LManager
import kotlinx.android.synthetic.main.activity_photo_chose.*
import org.jetbrains.anko.toast
import java.io.File
import java.io.FileOutputStream
import java.text.SimpleDateFormat
import java.util.*

class PhotoChoseActivity : Activity() {

    val PEMISSION_REQUEST = 11
    var CAMERA_PICTURE = 1
    var GALLERY_PICTURE = 2

    var fileName = ""
    var filePath = ""
    var compressFilePath = ""
    var compressFileName = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_photo_chose)

        checkMyPermission()

        photoChose_cameraBtn.setOnClickListener({ openCamera() })
        photoChose_galleryBtn.setOnClickListener({ showPiturePicker() })
        photoChose_cancelBtn.setOnClickListener({ finish() })

    }

    private fun checkMyPermission() {
        if (!PermissionUtil.isAllow(this, PermissionUtil.getCameraAndGalleryPemission())){
            ActivityCompat.requestPermissions(this,
                    PermissionUtil.getCameraAndGalleryPemission(),
                    PEMISSION_REQUEST
                    )
        }
    }

    /**
     * 从相机打开图片
     */
    fun openCamera(){
        /**
         * 防止造成崩溃和持有资源
         */
        if (isFinishing)
            return

        fileName = createFileName()
        var file = getFileByName(fileName)
        filePath = file.absolutePath
        var imageUri: Uri? = null
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            imageUri = FileProvider.getUriForFile(APP.getAppContext(), MConst.APPLICATION_ID + ".fileProvider", file)
        }else{
            imageUri = Uri.fromFile(file)
        }

        val openCameryintent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        openCameryintent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
        startActivityForResult(openCameryintent, CAMERA_PICTURE)
    }

    private fun createFileName():String  {
       return SimpleDateFormat("yyyyMMdd-HHmmss", Locale.CHINA)
                .format( Date()) + ".jpg"
    }

    private fun getFileByName(fileName: String): File{
        val externalStorageAvailable = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED
                || !Environment.isExternalStorageRemovable()

        var cachePath = ""
        if (externalStorageAvailable){
            cachePath = APP.getAppContext().getExternalCacheDir().path
        } else{
            cachePath = APP.getAppContext().cacheDir.path
        }
        var dir = File(cachePath + File.separator + MConst.APPLICATION_ID)
        if(!dir.exists())
            dir.mkdir()

        return File(cachePath, fileName)
    }

    /**
     * 从相册打开图片
     */
    fun showPiturePicker(){
        if (isFinishing)
            return
        // 不截取
        val openAlbumIntent = Intent(Intent.ACTION_PICK)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            openAlbumIntent.action = Intent.ACTION_OPEN_DOCUMENT// ACTION_GET_CONTENT
        } else {
            openAlbumIntent.action = Intent.ACTION_GET_CONTENT
        }
        openAlbumIntent.addCategory(Intent.CATEGORY_OPENABLE)
        openAlbumIntent.data = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        openAlbumIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        startActivityForResult(openAlbumIntent, GALLERY_PICTURE)
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.keep, R.anim.from_center_dim_out)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        finish()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>?, grantResults: IntArray?) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == PEMISSION_REQUEST){
            var isAlow = true
            grantResults?.forEach {
                if (it != PackageManager.PERMISSION_GRANTED){
                    isAlow = false
                }
            }
            if (isAlow){}
            else{
                toast("拒绝了权限")
                finish()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK){
            // 所有获取均返回文件地址
            when(requestCode){
                CAMERA_PICTURE->{
                    compress()
                    val msg = LAMessege()
                    msg.arg1 = compressFilePath
                    LManager.newInstance().trigger(LAction.ACTION_GET_LOCAL_IMAGE,msg)
                    finish()
                }
                GALLERY_PICTURE->{
                    // note ： 未压缩
                    var mPath = ""
                    if (data != null){
                        val uri = data.data
                        mPath = PhotoUtil.getPath(this,data.data)!!
                        if (!TextUtils.isEmpty(mPath)){
                            val msg = LAMessege()
                            msg.arg1 = mPath
                            LManager.newInstance().trigger(LAction.ACTION_GET_LOCAL_IMAGE,msg)
                            finish()
                        }
                    }
                }
            }
        }
    }

    private fun compress() {
        val bitmapUtils = BitmapUtils()
        var bitmap = bitmapUtils.compressForCamera(filePath)
        compressFileName = createFileName()
        var file = getFileByName(compressFileName)
        compressFilePath = file.absolutePath
        var os: FileOutputStream = FileOutputStream(compressFilePath)
        bitmap?.compress(Bitmap.CompressFormat.JPEG,100,os)
    }
}
